package com.vooda.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Json Web Token
 *
 * @author charlee
 * @date 2017年12月08日
 */
@Slf4j
public class JwtUtil {

    /**
     * 秘钥 任何情况下都不能向客户端传递
     */
    private final static String SECRET = "vooda7100";

    /**
     * 生成token
     *
     * @param userId 用户id
     * @return token
     */
    public static String createToken(Long userId) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        map.put("timestamp", System.currentTimeMillis());
        try {
            return JWT.create()
                    .withHeader(map)
                    .withClaim("userId", userId)
                    .sign(Algorithm.HMAC256(SECRET));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 校验token
     *
     * @param token token
     * @return userId;
     */
    public static Long validateToken(String token) {
        JWTVerifier verifier;
        try {
            verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            Map<String, Claim> claimMap = jwt.getClaims();
            return claimMap.get("userId").asLong();
        } catch (Exception e) {
            log.info(e.getMessage());
            return 0L;
        }
    }
}
